<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { userUploadAvatarService, updateUser } from '@/api/user'
import { userUserStore } from '@/stores'

const userStore = userUserStore()

const imgUrl = ref(userStore.img) //展示图片
const img = ref() //上传图片
const uploadRef = ref()

const onUploadFile = (file) => {
  console.log(file)
  // img.value = file.raw
  console.log(imgUrl.value)
  const fromData = new FormData()

  fromData.append('file', file.raw)
  img.value = fromData

  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
  }
}
//上传图片
const onUpdateAvatar = async () => {
  // console.log(imgUrl.value)
  const res = await userUploadAvatarService(img.value)
  console.log(res)
  await userStore.setImg(res.data.data) //存入头像
  await updateUser({ id: userStore.id, img: userStore.img }) //修改用户头像
  ElMessage({ type: 'success', message: '更换头像成功' })
}
</script>
<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>更换头像</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <img v-else src="@/assets/avatar.jpg" width="278" />
        </el-upload>
        <br />
        <el-button @click="uploadRef.$el.querySelector('input').click()" type="primary" :icon="Plus" size="large"
          >选择图片</el-button
        >
        <el-button type="success" :icon="Upload" size="large" @click="onUpdateAvatar"> 上传头像 </el-button>
      </el-col>
    </el-row>
  </el-card>
</template>
